<template>
  <BasicModal
    :title="t('layout.header.dropdownItemEditPass')"
    v-bind="$attrs"
    @register="register"
    @ok="handelSubmit"
    @cancel="handelCancel"
  >
    <BasicForm @register="registerForm"> </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { useI18n } from '@/hooks/web/useI18n';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { useAppStore } from '@/store/modules/app';
  import { POST } from '@/api/http';
  import { useUserStore } from '@/store/modules/user';
  import { useMessage } from '@/hooks/web/useMessage';

  const appStore = useAppStore();
  const { t } = useI18n();
  const [register, { closeModal }] = useModalInner(async () => {});
  const { createMessage } = useMessage();
  const userStore = useUserStore();

  const pswRules = [
    {
      validator(rule, value) {
        if (value?.length < 8) {
          return Promise.reject('密码长度不能小于8位');
        }
        if (value?.length > 15) {
          return Promise.reject('密码长度不能大于15位');
        }
        if (!/^(?=.*[A-Za-z])(?=.*\d)(?=.*[@#$!%*?&])[A-Za-z\d@#$!%*?&]+$/.test(value)) {
          return Promise.reject('密码必须包含字母、数字和特殊字符');
        }
        return Promise.resolve();
      },
    },
  ];

  const [registerForm, { validateFields, setFieldsValue }] = useForm({
    showActionButtonGroup: false,
    schemas: [
      {
        field: 'passWord',
        label: '原始密码',
        colProps: {
          span: 24,
        },
        componentProps: {
          placeholder: ' 输入原始密码',
        },
        required: true,
        component: 'InputPassword',
      },
      {
        field: 'newPassWord',
        label: '新的密码',
        component: 'InputPassword',
        componentProps: {
          placeholder: '输入新密码',
          showSearch: false,
          showArrow: true,
        },
        required: true,
        colProps: { span: 24 },
        rules: pswRules,
      },
      {
        field: 'confirmPassword',
        label: '确认密码',
        component: 'InputPassword',
        componentProps: {
          placeholder: '输入确认密码',
          showSearch: false,
          showArrow: true,
        },
        required: true,
        colProps: { span: 24 },
        rules: pswRules,
      },
    ],
  });
  const handelSubmit = async () => {
    try {
      const values = await validateFields();
      const { newPassWord, confirmPassword } = values;
      if (newPassWord !== confirmPassword) {
        createMessage.info('两次输入的密码不一致');
      }
      await POST('/membership/changeEmployeePassword', {
        passWord: values.passWord,
        newPassWord: values.newPassWord,
      });
      closeModal();
      createMessage.success('修改密码成功');
      userStore.logout(true);
    } catch (error) {
      return '';
    }
  };
  const handelCancel = () => {
    closeModal();
  };
</script>
